#!/usr/bin/env python
# encoding=utf-8
import datetime
import re
from utility import tail
import sys


def set_datetime_by_time_line(eventDic, line,events):
    events.append(eventDic)
    eventDic.clear()
    time_str = "20" + line.replace("# Time:", "").replace("  ", " ").strip()
    query_time = datetime.datetime.strptime(time_str, "%Y%m%d %H:%M:%S")
    eventDic['time'] = query_time
    print("set_datetime_by_time_line:" + str(eventDic['time']))

def set_timestamp(eventDic, line):
    result = re.findall("=([\S]+);", line)
    eventDic['timestamp'] = result[0]

def paserQueryLog(line, eventDic, events, tmpSQL):
    if line.startswith("# Time:"):
        set_datetime_by_time_line(eventDic, line)
    elif line.startswith("SET timestamp"):
        set_timestamp(eventDic, line)
    else:
        pass


if __name__ == '__main__':
    t = tail.Tail('/opt/app/percona_3306/logs/slow.log')
    t.register_callback(paserQueryLog)
    t.follow(s=5)